package org.codeart.map.remote;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.codeart.common.request.PointRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service
public class PointClient {

    @Value("${system.map.trace-points-upload-api}")
    private String pointsUploadApi;

    @Value("${system.map.key}")
    private String key;

    @Value("${system.map.sid}")
    private Integer sid;

    @Autowired
    private RestTemplate restTemplate;

    public boolean upload(PointRequest pointRequest) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>() {{
            add("key", key);
            add("sid", sid);
            add("tid", pointRequest.getTid());
            add("trid", pointRequest.getTrid());
            add("points", JSONObject.toJSONString(pointRequest.getPoints()));
        }};
        HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(map, headers);
        String json = restTemplate.postForObject(pointsUploadApi, request, String.class);
        JSONObject jsonObject = JSONObject.parseObject(json);
        log.info("高德地图: {}", json);
        String msg = jsonObject.getString("errmsg");
        return "OK".equals(msg);
    }

}
